from rest_framework.permissions import BasePermission
from apps.user.models import User


class PermissionInterceptor(BasePermission):

    def has_object_permission(self, request, view, obj):
        return self.has_permission(request, view)

    def has_permission(self, request, view):
        user: User = request.user
        user_permission = user.get_all_permissions()
        view_permission = getattr(view, 'permissions', None)
        if not view_permission:
            return True
        else:
            method_permission = view_permission.get(request.method.lower())
            for i in user_permission:

                if method_permission in i:
                    return True
            else:
                return False
